#ifndef PLOG_MULTIAPPENDER_LOGGER_H
#define PLOG_MULTIAPPENDER_LOGGER_H

#include <vector>
#include <algorithm>

#include "plog/logger.h"
#include "plog/log_message.h"
#include "plog/appender.h"

#include "plog/csv_formatter.h"

namespace plog
{
//////////////////////////////////////////////////////////////////////////

class write_to_appender
{
public:
    write_to_appender(log_level severity, const void* buffer, size_t length);
    void operator()(appender* log_appender);

private:
    log_level severity_;
    const void* buffer_;
    size_t length_;
};


//////////////////////////////////////////////////////////////////////////
// default loggers

class multiappender_logger 
    : public logger
{
public:
    multiappender_logger(){};
    ~multiappender_logger(){};
    
    void add_appender(appender* log_appender)
    {
        appenders_.push_back(log_appender);
        if (log_appender->newly_created())
        {
            csv_formatter formatter;
            log_appender->write(formatter.header(), formatter.header_size());
        }
    }

    void write(const message& msg)
    {
        csv_formatter formatter;
        formatter.format(msg);

        std::for_each(appenders_.begin(), appenders_.end(), write_to_appender(msg.severity(), formatter.buffer(), formatter.length()));
    }

    bool check_severity(log_level severity)
    {
        std::vector<appender*>::const_iterator it = std::min_element(appenders_.begin(), appenders_.end());

        if (it == appenders_.end() || (*it)->get_level() < severity)
            return false;

        return true;
    }


private:
    std::vector<appender*> appenders_;
};

//////////////////////////////////////////////////////////////////////////

}

#endif